// 在顶部导入部分添加Ant Design图标
import React, { useState, useEffect } from 'react';
import { Video, BarChart3, Eye, Target, Clock, Activity } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

import {
  Layout,
  Card,
  Statistic,
  Row,
  Col,
  Spin,
  Alert,
  Button,
  Tooltip
} from 'antd';
import {
  VideoCameraOutlined,
  EyeOutlined,
  AppstoreOutlined,
  LineChartOutlined
} from '@ant-design/icons';
import { Area, Column } from '@ant-design/plots';

// Import the API configuration
import API_CONFIG from '../utils/apiConfig';

const Dashboard = ({ onLogout = () => {} } = {}) => {
  const navigate = useNavigate();
  const [videoCount, setVideoCount] = useState(0);
  const [totalTargetCount, setTotalTargetCount] = useState(0);
  const [todayVideoCount, setTodayVideoCount] = useState(0);
  const [todayTargetCount, setTodayTargetCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [videos, setVideos] = useState([]);
  const [timeRange, setTimeRange] = useState('day'); // day, month
  const [chartData, setChartData] = useState({
    labels: [],
    videoCounts: [],
    targetCounts: []
  });
  const [objectTypeStats, setObjectTypeStats] = useState({});
  // 默认标签数据，确保即使API调用失败，图表也能正常显示
  const defaultLabels = ['公交车', '卡车', '摩托车', '汽车', '狗', '猫', '自行车', '行人', '长椅'];
  const [labels, setLabels] = useState(defaultLabels); // 存储从数据库获取的标签数据
  const [labelsLoading, setLabelsLoading] = useState(true);

  // 获取标签数据的effect
  useEffect(() => {
    console.log('开始加载标签数据...');
    // 修改loadLabels函数
    const loadLabels = async () => {
      try {
        setLabelsLoading(true);
        console.log('发起API请求: /api/labels');
        // 使用API_CONFIG替代硬编码路径
        const labelsData = await API_CONFIG.fetchJSON('labels');
        
        // 从对象数组中提取label_text字段，转换为字符串数组
        if (Array.isArray(labelsData)) {
          const labelTexts = labelsData.map(label => {
            // 确保只提取非空的label_text
            return label && typeof label.label_text === 'string' ? label.label_text : '';
          }).filter(label => label !== ''); // 过滤掉空字符串
          
          setLabels(labelTexts.length > 0 ? labelTexts : defaultLabels);
          console.log('从数据库获取的标签文本:', labelTexts);
        } else {
          setLabels(defaultLabels);
          console.log('API返回的数据格式不是数组，使用默认标签');
        }
      } catch (err) {
        console.error('加载标签数据失败:', err);
        console.log('使用初始默认标签数据');
      } finally {
        setLabelsLoading(false);
        console.log('标签加载完成，当前标签数据:', labels);
      }
    };
    
    loadLabels();
  }, []);
  
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 使用API_CONFIG替代硬编码IP和端口
        const videoData = await API_CONFIG.fetchJSON('videos');
        
        if (!Array.isArray(videoData)) {
          throw new Error('API返回的数据格式不正确');
        }
        
        setVideos(videoData);
        
        // 计算统计数据
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        const todayVideos = videoData.filter(video => {
          const videoDate = new Date(video.timestamp || video.start_time);
          return videoDate >= today;
        });
        
        setVideoCount(videoData.length);
        setTodayVideoCount(todayVideos.length);
        
        // 计算对象总数
        const totalObjects = videoData.reduce((sum, video) => {
          // 优先使用object_types数组长度，然后是objects数组长度，最后是objectCount
          if (video.object_types && Array.isArray(video.object_types)) {
            return sum + video.object_types.length;
          } else if (video.objects && Array.isArray(video.objects)) {
            return sum + video.objects.length;
          }
          return sum + (video.objectCount || 0);
        }, 0);
        
        const todayObjects = todayVideos.reduce((sum, video) => {
          if (video.object_types && Array.isArray(video.object_types)) {
            return sum + video.object_types.length;
          } else if (video.objects && Array.isArray(video.objects)) {
            return sum + video.objects.length;
          }
          return sum + (video.objectCount || 0);
        }, 0);
        
        setTotalTargetCount(totalObjects);
        setTodayTargetCount(todayObjects);
        
        // 生成图表数据
        generateChartData(videoData, timeRange);
        
        // 统计对象类型
        const objectStats = {};
        videoData.forEach(video => {
          // 处理多种可能的数据结构
          if (video.object_labels && Array.isArray(video.object_labels)) {
            // 优先使用预处理好的标签文本
            video.object_labels.forEach(label => {
              if (label) {
                const normalizedType = label.toLowerCase().trim();
                objectStats[normalizedType] = (objectStats[normalizedType] || 0) + 1;
              }
            });
          } else if (video.object_types && Array.isArray(video.object_types)) {
            // 其次使用object_types数组
            video.object_types.forEach(type => {
              // 处理可能是字符串或对象的类型
              const objectType = typeof type === 'string' ? type : 
                               (type.type || type.label || (typeof type === 'number' ? undefined : JSON.stringify(type)));
              if (objectType) {
                const normalizedType = objectType.toLowerCase().trim();
                objectStats[normalizedType] = (objectStats[normalizedType] || 0) + 1;
              }
            });
          } else if (video.objects && Array.isArray(video.objects)) {
            // 最后才考虑objects数组，并且过滤掉纯数字值
            video.objects.forEach(obj => {
              // 跳过纯数字值，只处理有type或label属性的对象
              if (typeof obj === 'number') return;
              
              const objectType = obj.type || obj.label || JSON.stringify(obj);
              if (objectType) {
                const normalizedType = objectType.toLowerCase().trim();
                objectStats[normalizedType] = (objectStats[normalizedType] || 0) + 1;
              }
            });
          } else if (video.object_types && typeof video.object_types === 'object') {
            Object.entries(video.object_types).forEach(([type, count]) => {
              objectStats[type] = (objectStats[type] || 0) + count;
            });
          }
        });
        
        // 确保所有从数据库获取的标签都有统计数据（即使为0）
        if (labels.length > 0) {
          labels.forEach(label => {
            const normalizedLabel = String(label || '').toLowerCase().trim();
            if (!objectStats.hasOwnProperty(normalizedLabel)) {
              objectStats[normalizedLabel] = 0;
            }
          });
        }
        
        setObjectTypeStats(objectStats);
      } catch (err) {
        console.error('加载数据失败:', err);
        setError(`加载数据失败: ${err.message}`);
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
    
    // 设置自动刷新
    const intervalId = setInterval(loadData, 5 * 60 * 1000);
    
    return () => clearInterval(intervalId);
  }, [timeRange]);

  // 生成图表数据
  const generateChartData = (videoData, range) => {
    const labels = [];
    const videoCounts = [];
    const targetCounts = [];
    
    if (range === 'day') {
      // 生成一天的数据（按小时）
      const now = new Date();
      for (let i = 23; i >= 0; i--) {
        const hour = new Date(now);
        hour.setHours(hour.getHours() - i);
        const hourStr = `${hour.getHours()}:00`;
        
        const hourVideos = videoData.filter(video => {
          const videoDate = new Date(video.timestamp || video.start_time);
          return videoDate.getHours() === hour.getHours() &&
                 videoDate.getDate() === hour.getDate() &&
                 videoDate.getMonth() === hour.getMonth() &&
                 videoDate.getFullYear() === hour.getFullYear();
        });
        
        const hourObjects = hourVideos.reduce((sum, video) => {
          if (video.object_types && Array.isArray(video.object_types)) {
            return sum + video.object_types.length;
          } else if (video.objects && Array.isArray(video.objects)) {
            return sum + video.objects.length;
          }
          return sum + (video.objectCount || 0);
        }, 0);
        
        labels.push(hourStr);
        videoCounts.push(hourVideos.length);
        targetCounts.push(hourObjects);
      }
    } else if (range === 'month') {
      // 生成一个月的数据（按天）
      const now = new Date();
      for (let i = 29; i >= 0; i--) {
        const day = new Date(now);
        day.setDate(day.getDate() - i);
        const dayStr = `${day.getMonth() + 1}/${day.getDate()}`;
        
        const dayVideos = videoData.filter(video => {
          const videoDate = new Date(video.timestamp || video.start_time);
          return videoDate.getDate() === day.getDate() &&
                 videoDate.getMonth() === day.getMonth() &&
                 videoDate.getFullYear() === day.getFullYear();
        });
        
        const dayObjects = dayVideos.reduce((sum, video) => {
          if (video.object_types && Array.isArray(video.object_types)) {
            return sum + video.object_types.length;
          } else if (video.objects && Array.isArray(video.objects)) {
            return sum + video.objects.length;
          }
          return sum + (video.objectCount || 0);
        }, 0);
        
        labels.push(dayStr);
        videoCounts.push(dayVideos.length);
        targetCounts.push(dayObjects);
      }
    }
    
    setChartData({ labels, videoCounts, targetCounts });
  };

  // 准备面积图数据，添加更严格的数据验证
  const areaPlotData = chartData.labels.map((label, index) => {
    // 确保value始终是有效的数字
    const count = chartData.videoCounts[index];
    const validValue = typeof count === 'number' && !isNaN(count) ? count : 0;
    
    return {
      time: label || '未知时间',
      value: validValue
    };
  });
  
  // 添加debug信息，帮助识别数据问题
  useEffect(() => {
    if (areaPlotData.length > 0) {
      // 检查数据中是否有null或undefined值
      const hasInvalidData = areaPlotData.some(item => 
        item.value === null || 
        item.value === undefined || 
        isNaN(item.value)
      );
      
      if (hasInvalidData) {
        console.log('检测到无效的面积图数据:', areaPlotData.filter(item => 
          item.value === null || 
          item.value === undefined || 
          isNaN(item.value)
        ));
      }
    }
  }, [areaPlotData]);

  // 准备柱状图数据 - 添加更严格的数据验证
  const columnPlotData = labels.map(label => {
    const normalizedLabel = String(label || '').toLowerCase().trim();
    const count = objectTypeStats[normalizedLabel] || 0;
    
    // 确保所有字段都有有效值
    return {
      type: String(label || '未知类型'), // 确保type字段不为undefined
      count: typeof count === 'number' && !isNaN(count) ? count : 0
    };
  });

  // 面积图配置
  const areaConfig = {
    data: areaPlotData,
    xField: 'time',
    yField: 'value',
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
    color: '#667eea',
    point: {
      shape: 'diamond',
      style: {
        fill: '#fff',
        strokeWidth: 2,
      },
    },
    legend: {
      position: 'top',
    },
    meta: {
      time: {
        alias: '时间',
      },
      value: {
        alias: '视频数',
      },
    },
    // 添加额外的安全配置
    interactions: [
      {
        type: 'element-active',
      },
    ],
    theme: 'light',
  };

  // 柱状图配置
  const columnConfig = {
    data: columnPlotData,
    xField: 'type',
    yField: 'count',
    label: {
      position: 'top',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
    },
    xAxis: {
      label: {
        autoRotate: true,
        autoHide: true,
        maxLength: 100,
      },
    },
    meta: {
      type: {
        alias: '对象类型',
      },
      count: {
        alias: '数量',
      },
    },
    color: '#667eea',
    // 添加额外的安全配置来防止 zIndex 错误
    interactions: [
      {
        type: 'element-active',
      },
    ],
    theme: 'light',
  };

  // 统计卡片数据 - 使用更漂亮的Ant Design图标
  const stats = [
    {
      title: '总视频数',
      value: videoCount,
      icon: <VideoCameraOutlined style={{ fontSize: '20px', color: 'white' }} />,
      color: '#667eea',
      suffix: ''
    },
    {
      title: '今日视频数',
      value: todayVideoCount,
      icon: <EyeOutlined style={{ fontSize: '20px', color: 'white' }} />,
      color: '#764ba2',
      suffix: ''
    },
    {
      title: '总对象数',
      value: totalTargetCount,
      icon: <AppstoreOutlined style={{ fontSize: '20px', color: 'white' }} />,
      color: '#f093fb',
      suffix: ''
    },
    {
      title: '今日对象数',
      value: todayTargetCount,
      icon: <LineChartOutlined style={{ fontSize: '20px', color: 'white' }} />,
      color: '#f5576c',
      suffix: ''
    }
  ];

  return (
    <Layout className="dashboard-layout" style={{ minHeight: '100vh', backgroundColor: '#f5f5f5' }}>
      <Layout.Content style={{ padding: '24px' }}>
        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: '24px' }}
          />
        )}
        
        <Spin spinning={loading} tip="数据加载中...">
          {/* 统计卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
            {stats.map((stat, index) => (
              <Col xs={12} sm={12} md={6} key={index}>
                <Card hoverable className="stat-card" style={{ borderRadius: '12px' }}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ backgroundColor: stat.color, borderRadius: '50%', width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', marginRight: '16px' }}>
                      {stat.icon}
                    </div>
                    <Statistic
                      title={stat.title}
                      value={stat.value}
                      precision={0}
                      valueStyle={{ color: '#2d3748' }}
                      suffix={stat.suffix}
                    />
                  </div>
                </Card>
              </Col>
            ))}
          </Row>

          {/* 时间范围选择器 */}
          <div className="time-range-selector" style={{ marginBottom: '24px', display: 'flex', gap: '12px', justifyContent: 'flex-start' }}>
            <Button
              type={timeRange === 'day' ? 'primary' : 'default'}
              onClick={() => setTimeRange('day')}
              icon={<Clock size={16} />}
              style={{
                borderRadius: '20px',
                paddingLeft: '16px',
                paddingRight: '16px'
              }}
            >
              按天
            </Button>
            <Button
              type={timeRange === 'month' ? 'primary' : 'default'}
              onClick={() => setTimeRange('month')}
              icon={<Activity size={16} />}
              style={{
                borderRadius: '20px',
                paddingLeft: '16px',
                paddingRight: '16px'
              }}
            >
              按月
            </Button>
          </div>

          {/* 图表区域 */}
          <Row gutter={[16, 16]}>
            <Col xs={24} md={12}>
              <Card hoverable title="视频数趋势" style={{ borderRadius: '12px' }}>
                {areaPlotData.length > 0 ? (
                  <Area {...areaConfig} />
                ) : (
                  <div style={{ textAlign: 'center', padding: '40px 0', color: '#718096' }}>
                    暂无数据
                  </div>
                )}
              </Card>
            </Col>
            <Col xs={24} md={12}>
              <Card hoverable title="对象类型统计" style={{ borderRadius: '12px' }}>
                {columnPlotData.length > 0 ? (
                  <Column {...columnConfig} />
                ) : (
                  <div style={{ textAlign: 'center', padding: '40px 0', color: '#718096' }}>
                    暂无数据
                  </div>
                )}
              </Card>
            </Col>
          </Row>
        </Spin>
      </Layout.Content>
    </Layout>
  );
};

// // Optional PropTypes validation
// Dashboard.propTypes = {
//   onLogout: PropTypes.func
// };

Dashboard.defaultProps = {
  onLogout: () => {}
};

export default Dashboard;

